package com.gz.springboot.config;


import com.gz.springboot.bean.Car;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 *  WebConfig是一个配置类
 *  proxyBeanMethods = false 使用Lite模式
 */
@Configuration(proxyBeanMethods = false)
public class WebConfig {

    //注入一个bean WebMvcConfigurer
    @Bean
    public WebMvcConfigurer webMvcConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addFormatters(FormatterRegistry registry) {
                //addFormatters,添加一个自定义的转换器
                //增加自定义转换器，String -> Monster
                //添加的转换器会注册到converters中
                //converters底层结构是ConcurrentHashMap，内置有124个转换器(默认)
                //加上这个那就共125个
                //如果在添加一个相同类型的转换器，会覆盖之前的，还是125个而不是变成126个
                registry.addConverter(new Converter<String, Car>() {
                    @Override
                    public Car convert(String source) {
                        if (!ObjectUtils.isEmpty(source)) {
                            Car car = new Car();
                            String[] split = source.split(",");
                            car.setName(split[0]);
                            car.setPrice(Double.parseDouble(split[1]));
                            return car;
                        }
                        return null;
                    }
                });
            }
        };
    }
}
